package cn.moonspace.flowerowner.service.impl;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;

import cn.moonspace.common.util.MyJsonUtil;
import cn.moonspace.flowerowner.entities.Car;
import cn.moonspace.flowerowner.entities.Comment;
import cn.moonspace.flowerowner.entities.Picture;
import cn.moonspace.flowerowner.entities.Upload;
import cn.moonspace.flowerowner.exception.DriverException;
import cn.moonspace.flowerowner.service.UploadService;

@Service("uploadService")
public class UploadServiceImpl extends BaseService implements UploadService { 

	@Override
	public JSONObject findUploadsForBack(Integer status, int pages, int pageSize, String dstDateFormat) throws DriverException {
		JSONObject result = new JSONObject();

		Sort sort = new Sort(new Order(Direction.DESC,"createDate"));
		Pageable pageable = new PageRequest(pages, pageSize, sort);
		
		Page<Upload> uploads = null;
		if(status != null){
			uploads = uploadRepository.findUploadsByStatus(status, pageable);
		}else{
			uploads = uploadRepository.findAll(pageable);
		}
		
		List<Upload> results = new ArrayList<Upload>();
		
		if(uploads == null || !uploads.hasContent()){
			result.put("error", "车不奇葩枉少年");
		}else{
			for(Upload upload : uploads.getContent()){
				try {
					results.add(upload.clone());
				} catch (CloneNotSupportedException e) {
					DriverException de = new DriverException(DriverException.UploadCloneException, "Upload Clone Error: " + e.getMessage(), this.getClass().getName());
					de.setStackTrace(e.getStackTrace());
					throw de;
				}
			}
			JSONArray arrUploads = JSONArray.fromObject(results, MyJsonUtil.getConfig(dstDateFormat));
			result.put("results", arrUploads);
		}
		return result;
	}

	@Override
	public JSONObject findUploadsForFront(int pages, int pageSize, String dstDateFormat) throws DriverException {
		JSONObject result = new JSONObject();

		Sort sort = new Sort(new Order(Direction.DESC,"createDate"));
		Pageable pageable = new PageRequest(pages, pageSize, sort);
		
		Page<Upload> uploads = uploadRepository.findUploadsByStatus(Upload.STATUS_PASS, pageable); 
		
		List<Upload> results = new ArrayList<Upload>();
		
		if(uploads == null || !uploads.hasContent()){
			result.put("error", "车不奇葩枉少年");
		}else{
			for(Upload upload : uploads.getContent()){
				try {
					results.add(upload.clone());
				} catch (CloneNotSupportedException e) {
					DriverException de = new DriverException(DriverException.UploadCloneException, "Upload Clone Error: " + e.getMessage(), this.getClass().getName());
					de.setStackTrace(e.getStackTrace());
					throw de;
				}
			}
			JSONArray arrUploads = JSONArray.fromObject(results, MyJsonUtil.getConfig(dstDateFormat));
			result.put("results", arrUploads);
		}
		return result;
	}

	@Override
	public JSONObject findUploadsForFront(String search, int pages, int pageSize, String dstDateFormat) throws DriverException {
		if(search == null || search.length() <= 0){
			return findUploadsForFront(pages, pageSize, dstDateFormat);
		}
		
		JSONObject result = new JSONObject();

		Sort sort = new Sort(new Order(Direction.DESC,"createDate"));
		Pageable pageable = new PageRequest(pages, pageSize, sort);
		
		Page<Upload> uploads = null;
		if(Arrays.asList(Car.AREA_SET).contains(search.substring(0,1))){
			uploads = uploadRepository.findUploadsByMultiConds(search.substring(0,1), search.substring(1), Upload.STATUS_PASS, pageable);
		}else{
			uploads = uploadRepository.findUploadsByMultiConds("%"+search+"%", Upload.STATUS_PASS, pageable);
		}
		
		List<Upload> results = new ArrayList<Upload>();
		
		if(uploads == null || !uploads.hasContent()){
			result.put("error", "车不奇葩枉少年");
		}else{
			for(Upload upload : uploads.getContent()){
				try {
					results.add(upload.clone());
				} catch (CloneNotSupportedException e) {
					DriverException de = new DriverException(DriverException.UploadCloneException, "Upload Clone Error: " + e.getMessage(), this.getClass().getName());
					de.setStackTrace(e.getStackTrace());
					throw de;
				}
			}
			JSONArray arrUploads = JSONArray.fromObject(results, MyJsonUtil.getConfig(dstDateFormat));
			result.put("results", arrUploads);
		}
		return result;
	}

	@Override
	public JSONObject findUploadsForApp(String search, int pages, int pageSize, String dateStr, String orgDateFormat, String dstDateFormat) throws DriverException {
		if(dateStr == null || dateStr.length() <= 0){
			return findUploadsForFront(search, pages, pageSize, dstDateFormat);
		}
		
		JSONObject result = new JSONObject();

		Sort sort = new Sort(new Order(Direction.DESC,"createDate"));
		Pageable pageable = new PageRequest(pages, pageSize, sort);
		
		SimpleDateFormat sdf = new SimpleDateFormat(orgDateFormat);  
		Date date = new Date();
		try {
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
			DriverException de = new DriverException(DriverException.DateParseException, "Date Parse Error: " + e.getMessage(), this.getClass().getName());
			de.setStackTrace(e.getStackTrace());
			throw de;
		}
		
		Page<Upload> uploads = null;
		if(search == null || search.length() <= 0){
			uploads = uploadRepository.findUploadsByStatus(Upload.STATUS_PASS, date, pageable);
		}else if(Arrays.asList(Car.AREA_SET).contains(search.substring(0,1))){
			uploads = uploadRepository.findUploadsByMultiConds(search.substring(0,1), search.substring(1), Upload.STATUS_PASS, date, pageable);
		}else{
			uploads = uploadRepository.findUploadsByMultiConds("%"+search+"%", Upload.STATUS_PASS, date, pageable);
		}
		
		List<Upload> results = new ArrayList<Upload>();
		
		if(uploads == null || !uploads.hasContent()){
			result.put("error", "车不奇葩枉少年");
		}else{
			for(Upload upload : uploads.getContent()){
				try {
					results.add(upload.clone());
				} catch (CloneNotSupportedException e) {
					DriverException de = new DriverException(DriverException.UploadCloneException, "Upload Clone Error: " + e.getMessage(), this.getClass().getName());
					de.setStackTrace(e.getStackTrace());
					throw de;
				}
			}
			JSONArray arrUploads = JSONArray.fromObject(results, MyJsonUtil.getConfig(dstDateFormat));
			result.put("results", arrUploads);
		}
		return result;
	}

	@Override
	public JSONObject updateUploadStatus(Long id, int status) {
		JSONObject result = new JSONObject();
		Upload upload = uploadRepository.findOne(id);
		upload.setStatus(status);
		upload.setCheckTime(new Date());
		uploadRepository.save(upload);
		result.put("result", "OK");
		
		return result;
	}

	@Override
	public JSONObject delUpload(Long id, String realPath) {
		JSONObject result = new JSONObject();
		Upload upload = uploadRepository.findOne(id);
		for(Picture picture : upload.getPictures()){
			File imageFile = new File(realPath, picture.getImagePath());
			File thumbFile = new File(realPath, picture.getThumbPath());
			File thumbLargeFile = new File(realPath, picture.getThumbPathLarge());
			if (imageFile.isFile() && imageFile.exists()) {  
				imageFile.delete();  
		    }
			if (thumbFile.isFile() && thumbFile.exists()) {  
				thumbFile.delete();  
		    }
			if (thumbLargeFile.isFile() && thumbLargeFile.exists()) {  
				thumbLargeFile.delete();  
		    }
			pictureRepository.delete(picture);
		}
		for(Comment comment : upload.getComments()){
			commentRepository.delete(comment);
		}
		uploadRepository.delete(upload);
		result.put("result", "OK");
		return result;
	}
	
}
